package com.smartcruise.util.network;

import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.CannedAccessControlList;
import com.alibaba.sdk.android.oss.model.CreateBucketRequest;
import com.alibaba.sdk.android.oss.model.CreateBucketResult;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.smartcruise.MyApplication;
import com.smartcruise.util.FileUtils;
import com.smartcruise.util.network.callBack.UploadFileCallBack;

import java.util.Random;

/**
 * Created by FengChaoQun
 * on 2018/2/8 0008
 * oss上传的操作
 */

public class OssManager {

    private static final String endpoint = "oss-cn-shanghai.aliyuncs.com";
    private static final String accessKeyId = "LTAIb7QEsbiTEScz";
    private static final String secretKeyId = "ksDvHGNzmG5eBfm9M12XSMbfC9vM5K";
    private static final String bucket = "smart-cruise-test-bucket";
    //    private static final String endpoint = "oss-cn-hangzhou.aliyuncs.com";
//    private static final String accessKeyId = "LTAIb82HXAtXgihB";
//    private static final String secretKeyId = "fW8BGKdYrMkt8jdOM0A0eiCO4u70tB";
//    private static final String bucket = "fcq-test-bucket";
    private static OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, secretKeyId);
    private static ClientConfiguration conf = new ClientConfiguration();
    private static OSS oss = new OSSClient(MyApplication.getInstance(), endpoint, credentialProvider);

    public static void upLoadTest() {
        byte[] uploadData = new byte[100 * 1024];
        new Random().nextBytes(uploadData);
        PutObjectRequest put = new PutObjectRequest(bucket, "testObject", uploadData);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });
        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
                Log.d("ETag", result.getETag());
                Log.d("RequestId", result.getRequestId());
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
    }

    public static void createBucket() {
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucket);
        createBucketRequest.setBucketACL(CannedAccessControlList.PublicRead); // 指定Bucket的ACL权限
        createBucketRequest.setLocationConstraint("oss-cn-shanghai"); // 指定Bucket所在的数据中心
        OSSAsyncTask createTask = oss.asyncCreateBucket(createBucketRequest, new OSSCompletedCallback<CreateBucketRequest, CreateBucketResult>() {
            @Override
            public void onSuccess(CreateBucketRequest request, CreateBucketResult result) {
                Log.d("locationConstraint", request.getLocationConstraint());
            }

            @Override
            public void onFailure(CreateBucketRequest request, ClientException clientException, ServiceException serviceException) {
                // 请求异常
                if (clientException != null) {
                    // 本地异常如网络异常等
                    clientException.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
    }

    public OSSAsyncTask upLoadFile(String filePath, String key, final UploadFileCallBack callBack) {
        PutObjectRequest put = new PutObjectRequest(bucket, key, filePath);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                if (callBack != null) {
                    callBack.onProgress(request, currentSize, totalSize);
                }
            }
        });
        if (callBack != null) {
            callBack.onStart();
        }
        return oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                if (callBack != null) {
                    callBack.onSuccess(request, result);
                }
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                if (callBack != null) {
                    callBack.onFailure(request, clientExcepion, serviceException);
                }
            }
        });
    }

    public static OSS getOss() {
        return oss;
    }

    public static String getBucket() {
        return bucket;
    }

    public static final String ossHead = "http://" + bucket + "." + endpoint + "/";

    public static String getOssUrl(String fileName) {
        return ossHead + fileName;
    }

    public static boolean isOssUrl(String url) {
        return url != null && url.contains("oss");
    }

    public static String getOriginalName(String url) {
        if (url == null) {
            return null;
        }
        return url.replace(ossHead, "").replace(FileUtils.THUMBNAIL_SUFFIX, "");
    }

}
